package com.xl.juc.lock;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 独占锁（写锁） 一次只能被一个线程占有
 * 共享锁（读锁）多个线程可以同时占有
 * 读写锁
 *
 * 读-读 可以共存
 * 读-写 不可以共存
 * 写-写 不可以共存
 * @author Charley
 * @create 2021-01-24
 */
public class ReadWriteLock {
    public static void main(String[] args) {
        myCashLock myCash = new myCashLock();
        //写入
        for (int i = 1; i <=5 ; i++) {
            int finalI = i;
            new Thread(()->{
                myCash.set(finalI +"",finalI+"");
            },String.valueOf(i)).start();
        }
        //读取
        for (int i = 1; i <=5 ; i++) {
            int finalI = i;
            new Thread(()->{
                myCash.get(finalI +"");
            },String.valueOf(i)).start();
        }
    }

}
//自定义没加锁 顺序混乱
class myCash{
    private volatile Map<String,Object> map= new ConcurrentHashMap<>();

    public void set(String key,Object val){
        System.out.println(Thread.currentThread().getName()+"写入");
        map.put(key,val);
        System.out.println(Thread.currentThread().getName()+"写入ok");
    }

    public void get(String key){
        System.out.println(Thread.currentThread().getName()+"读取");
        map.get(key);
        System.out.println(Thread.currentThread().getName()+"读取ok");
    }
}

/**
 * 加入读写锁：只有一个线程去写入  多个线程读取
 * 1写入
   1写入ok
 */
class myCashLock{
    private volatile Map<String,Object> map= new ConcurrentHashMap<>();
    ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    public void set(String key,Object val){
        try {
            readWriteLock.writeLock().lock();
            System.out.println(Thread.currentThread().getName()+"写入");
            map.put(key,val);
            System.out.println(Thread.currentThread().getName()+"写入ok");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readWriteLock.writeLock().unlock();
        }
    }

    public void get(String key){
        try {
            readWriteLock.readLock().lock();
            System.out.println(Thread.currentThread().getName()+"读取");
            map.get(key);
            System.out.println(Thread.currentThread().getName()+"读取ok");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readWriteLock.readLock().unlock();
        }
    }
}